<script setup>
import { ref } from 'vue';
import {
  getRoleListService,
  getUserRolesService,
  setUserRolesService
} from '@/apis/system-manage';

const roleList = ref([]);
let mUserId = '';
const userRolesModel = ref([]);

const loading = ref(false);

let isGiveupWarning = false;
const handleClose = (done) => {
  if (!isGiveupWarning) {
    ElMessage.warning('当前的 权限 未保存，放弃保存请再次点击取消');
    isGiveupWarning = true;
    setTimeout(() => {
      isGiveupWarning = false;
    }, 3000);
    return;
  }

  if (done) {
    done();
  } else {
    dialogVisible.value = false;
  }
};

const dialogVisible = ref(false);
const open = async (userId) => {
  mUserId = userId;
  userRolesModel.value = [];

  dialogVisible.value = true;
  loading.value = true;
  Promise.all([getRoleListService({}), getUserRolesService({ userId: userId })])
    .then((resArr) => {
      loading.value = false;

      let roleRes = resArr[0];
      let userRoleRes = resArr[1];

      roleList.value = roleRes.data;
      userRolesModel.value = userRoleRes.data.map((a) => a.id);
    })
    .catch(() => {
      loading.value = false;
    });
};

defineExpose({
  open
});

const onConfirm = async () => {
  loading.value = true;
  let res = await setUserRolesService({
    userId: mUserId,
    roleIds: userRolesModel.value
  });
  loading.value = false;
  ElMessage.success(res.msg);
  dialogVisible.value = false;
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑权限"
    width="30%"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form v-loading="loading" ref="roleModelRef" label-width="100px">
      <el-form-item label="角色">
        <el-checkbox-group v-model="userRolesModel">
          <el-checkbox
            v-for="(item, index) in roleList"
            :key="index"
            :label="item.id"
          >
            {{ `${item.roleName}【${item.roleCode}】` }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="onConfirm">确认</el-button>
        <el-button @click="handleClose()">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.role-icon-container i {
  font-size: 30px;
  margin-left: 30px;
}
</style>
